﻿using System.Dynamic;
using AzureDiagMon.Common;
using AzureDiagMon.Common.Helpers;
using AzureDiagMon.Common.Mvvm.Helpers;
using GalaSoft.MvvmLight;

namespace AzureDiagMon.ViewModels
{
    /// <summary>
    /// Dynamic ViewModel locator
    /// </summary>
    public class ViewModelLocator : DynamicObject
    {
        #region Constructor

        public ViewModelLocator()
        {
            if (ViewModelBase.IsInDesignModeStatic)
            {
                Bootstrapper.Startup();
            }
            else
            {
                IoC.Inject(this);
            }
        }

        #endregion

        #region Helper methods

        public static void Cleanup()
        {
            var main = IoC.Get<MainViewModel>();
            if (main != null)
            {
                main.Cleanup();
            }
        }

        #endregion

        #region Overriden members

        /// <summary>
        /// Overridden TryGetMember: The Dynamic View Model resolver
        /// </summary>
        /// <param name="binder"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = ViewModelHelper.GetViewModel(binder.Name);

            if (result != null)
                return true;

            return base.TryGetMember(binder, out result);
        }

        #endregion
    }
}